#include "ccms/nr/utils.h"
#include "arlib/exception/runtime_exception.h"
#include <sys/types.h>
#include <pwd.h>

#define THROW_RUNTIMEEXCEPTION(reason) throw arlib::exception::RuntimeException(__FILE__, __LINE__, reason)

using namespace ccms::nr;

namespace ccms {
namespace nr {

Utils::Utils() {
}

void Utils::getUsername(const uid_t uid, std::string* bufferPtr)
{
    struct passwd* passwdEntryPtr = NULL;
    std::string username;

    while((passwdEntryPtr = getpwent()) != NULL) {
        if(passwdEntryPtr->pw_uid == uid) {
            username = passwdEntryPtr->pw_name;
            break;
        }
    }

    endpwent();

    if(username.length() != 0) {
        *bufferPtr = username;
    } else {
        THROW_RUNTIMEEXCEPTION("Could not resolve user name");
    }
}

} // namespace nr
} // namespace ccms
